<script setup lang="ts">
  import { assignEngineer } from '@/api/order'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import useServicePersonalOptions from '@/components/pages/order/list/assign-network/services/useServicePersonalOptions'
  import { FormInstance } from 'element-plus'
  import _ from 'lodash'
  import { PropType, ref, watch } from 'vue'

  defineOptions({
    name: 'OrderDetailAssignEngineerModal',
  })

  const { servicePersonalOptions, getServicePersonalOptionsLoading, getServicePersonalOptions } =
    useServicePersonalOptions()

  const props = defineProps({
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  const visible = defineModel('modelValue', { type: Boolean, default: false })
  const getEngineerOptionsKeyword = ref('')
  const formInstance = ref<FormInstance | null>(null)
  const formRules = {
    networkEmpId: [{ required: true, message: '工程师为必填项', trigger: ['change', 'blur'] }],
  }
  const form = ref<OrderDetailAPiRequest.AssignEngineerForm>({
    networkEmpId: '',
    networkId: '',
    remark: '',
    workIds: [],
  })
  const formSaveLoading = ref(false)

  const submit = async () => {
    try {
      formSaveLoading.value = true
      const res = await assignEngineer(form.value)
      formSaveLoading.value = false
      return res.data
    } catch (error) {
      formSaveLoading.value = false
    }
  }

  const resetForm = () => {
    form.value = {
      networkEmpId: '',
      networkId: '',
      remark: '',
      workIds: [],
    }
  }

  const hideDialog = () => {
    resetForm()
    visible.value = false
  }

  const engineerSelectFilterMethod = _.debounce((keyword: string) => {
    if (getEngineerOptionsKeyword.value !== keyword) {
      getEngineerOptionsKeyword.value = keyword
      getServicePersonalOptions(getEngineerOptionsKeyword.value, form.value.networkId)
    }
  })

  const onConfirm = async () => {
    if (!formInstance.value) {
      return
    }

    try {
      await formInstance.value.validate()
      const res = await submit()
      if (res.code === 20000) {
        HMessage.success('分派完成')
        emits('update')
        hideDialog()
        return
      }
      HMessageBox.error(res.message)
    } catch (error) {
      // error
    }
  }

  watch(visible, (value) => {
    if (value) {
      form.value.networkId = props.orderDetail.networkId
      form.value.workIds = [props.orderDetail.id]
      getServicePersonalOptions(getEngineerOptionsKeyword.value, form.value.networkId)
    }
  })
</script>

<template>
  <h-dialog v-model="visible" :loading="formSaveLoading" @close="hideDialog">
    <el-form
      ref="formInstance"
      inline-message
      label-position="top"
      class="modal_form_content"
      :rules="formRules"
      :model="form"
    >
      <el-form-item label="网点名称">
        <el-input :model-value="props.orderDetail.network" disabled />
      </el-form-item>

      <el-form-item label="工程师" prop="networkEmpId">
        <el-select
          v-model="form.networkEmpId"
          :loading="getServicePersonalOptionsLoading"
          placeholder="请选择工程师"
          filterable
          :filter-method="engineerSelectFilterMethod"
        >
          <el-option
            v-for="(item, index) in servicePersonalOptions"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model.trim="form.remark"
          type="textarea"
          placeholder="请输入备注"
          input-style="height: 120px;"
          :maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <h-button is-modal type="primary" @click="onConfirm">确定</h-button>
      <h-button is-modal @click="hideDialog">取消</h-button>
    </template>
  </h-dialog>
</template>
